/**
手动发货：这里针对待发货的订单可以直接操作修改状态变为已发货状态、

点击时需要判断是否勾选了订单，若没有勾选订单，则提示：请先勾选订单数据、

若勾选了数据，则这里的弹窗内的订单数为勾选的数据（需要把没有物流单号的数据剔除掉）

输入包裹重量为必填项，最小值为0.01
 *
 *  */
/**
 * desc: 合格证打印弹框页面
 */
import { CommonForm } from "@/pages/OrderModule/common/components/CommonForm";
import CommonModal from "@/components/CommonModal";
import { Form, Select, message } from "antd";
import { useState, useEffect } from "react";
import { getOutboundNoCertificatePrintData } from '../../../service.js';
import { printKmUniqcode } from '@/utils/printKm.js';
import { getAllPrinter } from "./print.jsx";
import { setExpressRelativePrinter, getExpressRelativePrinter } from "@/utils/authority";

const ActionModal = props => {
	const { selectedRows } = props;

	const printObj = getExpressRelativePrinter() || {};

	const [form] = Form.useForm();

	const [printerOnlineList, setPrinterOnlineList] = useState([]);

	const [open, setOpen] = useState(false);

	//是否正在打印
	const [isPrint, setIsPrint] = useState(false);

	useEffect(() => {
		form.setFieldsValue({
			printer: printObj["合格证"]
		});
		setOpen(true);
		getAllPrinter(value => setPrinterOnlineList(value));
	}, []);

	function handleOk() {
		form.submit();
	}
	//点击打印
	const onFinish = () => {
		form
			.validateFields()
			.then(async value => {
				if (!selectedRows?.length) {
					return message.info("打印数据为空");
				}
				if (!value.printer) {
					return message.info("请选择打印机");
				}
				if (isPrint) {
					return message.info('打印作业正在进行中，请勿重复提交');
				}
				START_LOADING();
				const arr = selectedRows.map(v => v.outboundNo);
				const res = await getOutboundNoCertificatePrintData(arr);
				END_LOADING();
				if (res.success) {
					setIsPrint(true);
					message.info('即将开始打印');
					printKmUniqcode(JSON.parse(res.data), value["printer"], () => {
						setIsPrint(false);
						setOpen(false);
					});
				}
			})
			.catch(err => {
				console.log(err);
			});
	};

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		props.onCancel();
	}

	// 设置打印机名称
	const handlePrinterName = name => {
		setExpressRelativePrinter({
			...printObj,
			"合格证": name
		});
	};

	return (
		<CommonModal title="合格证打印" afterClose={afterClose} open={open} width="530px" onCancel={onCancel} onOk={handleOk}>
			{/* <Alert type="info" message={<Typography as="s1">可发货订单数：{props.selectedRows.length}</Typography>} />
			 */}
			<CommonForm
				formProps={{
					form,
					onFinish
				}}
				columns={[
					{
						label: "订单数量",
						slot: <>{props.selectedRows.length}</>
					},
					{
						Component: Select,
						name: "printer",
						label: "打印机",
						rules: [{ required: true, message: "请选择打印机" }],
						props: {
							placeholder: "请选择打印机",
							onChange: handlePrinterName,
							options: printerOnlineList.map(d => ({
								value: d,
								label: d
							}))
						}
					}
				]}
			></CommonForm>
		</CommonModal>
	);
};

export default ActionModal;
